package com.example.framework;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {
	
	//create constructor for GroupHelper, give him parameter - link to appmanager
	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}

	public Set<GroupObject> getGroups() {
		manager.getNavigationHelper().gotoGroupList();
		//get list of data from Groups Page
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		//empty set of checkboxes
		Set<GroupObject> groups = new HashSet<GroupObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			title = title.substring("Select (".length(), title.length()-")".length());
			GroupObject group = new GroupObject()
				.setName(title)
				.setId(checkbox.getAttribute("value"));
			groups.add(group);
		}
		return groups;
	}
	
	public void createGroup(GroupObject groupObject) {
		manager.getNavigationHelper().gotoGroupList();
		initGroupCreation();
		fillGroupForm(groupObject);
		submitGroupCreation();
		manager.getNavigationHelper().gotoGroupList();
	}
	
	public void deleteGroup(GroupObject groupObject) {
		manager.getNavigationHelper().gotoGroupList();
		checkGroupBox(groupObject);
		click(By.name("delete"));
		manager.getNavigationHelper().gotoGroupList();
	}
	
	public void editGroup(GroupObject groupObject) {
		manager.getNavigationHelper().gotoGroupList();
		initGroupEditing(groupObject);
		fillGroupForm(groupObject);
		submitGroupEditing();
		manager.getNavigationHelper().gotoGroupList();
	}

	private void initGroupEditing(GroupObject groupObject) {
		checkGroupBox(groupObject);
		click(By.name("edit"));
	}
	
	private void checkGroupBox(GroupObject groupObject) {
		findElement(By.xpath("(//input[@name='selected[]'])[1]")).click();
	}

	private void initGroupCreation() {
		click(By.name("new"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}

	private void submitGroupCreation() {
		click(By.name("submit"));
	}

	private void submitGroupEditing() {
		click(By.name("update"));
	}
}
